package youleche.com.caches;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

import youleche.com.business.BBaseParamInfo;
import youleche.com.connection.ConnectionParameters;
import youleche.com.util.DateUtil;

/**
 * 基础参数缓存
 * @author Administrator
 *
 */
public class BaseParamInfoCache {
	/**
	 * 缓存时间
	 */
	private static int intenalMinutes = 0;
	
	/**
	 * 缓存对象
	 */
	private static Object obj = null;
	
	/**
	 * 最后一次更新时间
	 */
	private static Date lastTime = null;
	
	/**
	 * 设置缓存
	 * @param obj 缓存内容
	 */
	private static void setCache(Object object){
		obj = object;
		lastTime = DateUtil.getNowDate();
	}

	/**
	 * 更新缓存
	 */
	public static void updateCache(){
		BBaseParamInfo infoBusi = new BBaseParamInfo();
		try {
			setCache(infoBusi.getBaseParamInfoList());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 获取缓存（基础参数信息）
	 * @return 缓存
	 * @throws Exception 抛出异常
	 */
	public static Object getCache() throws Exception{
		if(lastTime == null){
			lastTime = DateUtil.getNowDate();
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		int minutes = (int)DateUtil.getDateDiffMinutes(sdf.format(lastTime), sdf.format(DateUtil.getNowDate()));
		intenalMinutes = getCacheTime();
		if(obj == null || minutes > intenalMinutes){
			////异步重新获取缓存
			BBaseParamInfo infoBusi = new BBaseParamInfo();
			setCache(infoBusi.getBaseParamInfoList());
			//AsynFactory.asynInvoke(BBaseParamInfo.class, "getBaseParamInfoList", null);
		}
		
		return obj;
	}

	/**
	 * 获取缓存时间
	 * @return 缓存时间
	 */ 
	private static int getCacheTime(){
		Properties properties=new Properties();
		try {
			properties.load(ConnectionParameters.class.getClassLoader().getResourceAsStream("cacheTime.properties"));
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		String time =(String) properties.get("time"); 
		
		return Integer.parseInt(time);
	}
}
